<?php

include_once 'DBCon.php';
include_once 'Utilities.php';
include_once 'lib/swiftmalier/swift_required.php';

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of User
 *
 * @author Kenny
 */
class User {

    private $con;
    private $username;
    private $uid;
    private $password;
    private $question;
    private $answer;
    private $email;
    private $groupId;
    private $salt = "A3/-osv$0-231@#SC34zsd8fq]tj34&41dsjyj70u2%7vw4>[:l-==";
    private $loginbyusername = 'SELECT uid, username, password, groupId FROM users WHERE username = ?;';
    private $loginbyuid = 'SELECT uid, username, password, groupId FROM users WHERE uid = ?;';
    private $recoverpassword = 'SELECT uid, username, question, answer, email FROM users WHERE username = ?;';
    private $createuser = 'INSERT INTO users(username, password, question, answer, email, registerDate, groupId) VALUES(?,?,?,?,?,?,?);';
    private $selectpassword = 'SELECT password FROM users WHERE uid = ?;';
    private $updatepassword = 'UPDATE users SET password = ? WHERE uid = ?;';
    private $checkemail = 'SELECT email FROM users WHERE email = ?;';

    function __construct() {
        $this->con = DBCon::connectDB();
    }

    public function loginByUsername($username, $password) {
        $pstmt = $this->con->prepare($this->loginbyusername);
        $pstmt->bind_param('s', $username);
        if ($pstmt->execute()) {
            $pstmt->bind_result($this->uid, $this->username, $this->password, $this->groupId);
            if ($pstmt->fetch()) {
                if (hash('sha256', $this->salt . $password) === $this->password) {
                    session_start();
                    $_SESSION['username'] = $this->username;
                    $_SESSION['uid'] = $this->uid;
                    $_SESSION['groupId'] = $this->groupId;
                } else {
                    return 1;
                }
            } else {
                return 2;
            }
            return 3;
        } else {

            return 0;
        }
    }

    public function loginByUid($uid, $password) {
        $pstmt = $this->con->prepare($this->loginbyuid);
        $pstmt->bind_param('s', $uid);
        if ($pstmt->execute()) {
            $pstmt->bind_result($this->uid, $this->username, $this->password, $this->groupId);
            if ($pstmt->fetch()) {
                if (hash('sha256', $this->salt . $password) === $this->password) {
                    session_start();
                    $_SESSION['username'] = $this->username;
                    $_SESSION['uid'] = $this->uid;
                    $_SESSION['groupId'] = $this->groupId;
                } else {
                    return 1;
                }
            } else {
                return 2;
            }
            return 3;
        } else {
            return 0;
        }
    }

    public function createUser() {
        $username = trim($_POST['user']);
        $password = hash('sha256', $this->salt . trim($_POST['password']));
        $question = trim($_POST['question']);
        $answer = trim($_POST['answer']);
        $email = trim($_POST['email']);
        $registerDate = date('Y/m/d');
        $groupId = 3;
        $pstmt = $this->con->prepare($this->createuser);
        $pstmt->bind_param('sssssss', $username, $password, $question, $answer, $email, $registerDate, $groupId);
        $pstmt->execute();
        if ($pstmt->affected_rows > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function checkPassword() {
        $password = hash('sha256', $this->salt . trim($_POST['password']));
        $uid = trim($_POST['uid']);
        $pstmtselect = $this->con->prepare($this->selectpassword) or die($this->con->error);
        $pstmtselect->bind_param('s', $uid);
        $pstmtselect->execute();
        $pstmtselect->bind_result($this->password);
        if ($pstmtselect->fetch()) {
            if ($password == $this->password) {
                return true;
            } else {
                return false;
            }
        }
    }

    public function changePassword() {
        $current = hash('sha256', $this->salt . trim($_POST['current']));
        $new = hash('sha256', $this->salt . trim($_POST['new']));
        $confirmnew = hash('sha256', $this->salt . trim($_POST['confirm']));
        $uid = trim($_POST['uid']);
        $pstmtselect = $this->con->prepare($this->selectpassword) or die($this->con->error);
        $pstmtupdate = $this->con->prepare($this->updatepassword) or die($this->con->error);
        $pstmtselect->bind_param('s', $uid);
        $pstmtselect->execute();
        $pstmtselect->store_result();
        $pstmtselect->bind_result($this->password);
        if ($pstmtselect->fetch()) {
            if ($current == $this->password) {
                if ($new == $confirmnew) {
                    $pstmtupdate->bind_param('ss', $new, $uid);
                    $pstmtupdate->execute();
                    if ($pstmtupdate->affected_rows > 0) {
                        //password changed successfully
                        return 4;
                    }
                    //password did not change successfully
                    return 3;
                } else {
                    //new password entered did not match
                    return 2;
                }
            } else {
                //current password did not match
                return 1;
            }
        } else {
            //database error
            return 0;
        }
    }

    private function sendEmail($receiver, $content) {
        $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
                ->setUsername('railway.no.reply@gmail.com')
                ->setPassword('Railway0123');

        $mailer = Swift_Mailer::newInstance($transport);

        $message = Swift_Message::newInstance('Request for password retrieval')
                ->setFrom(array('railway.no.reply@gmail.com' => 'Railway Website Customer Service'))
                ->setTo($receiver)
                ->setBody($content, 'text/html');

        $result = $mailer->send($message);
        return $result;
    }
    
    public function sendEmail2($receiver, $content) {
        $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
                ->setUsername('railway.no.reply@gmail.com')
                ->setPassword('Railway0123');

        $mailer = Swift_Mailer::newInstance($transport);

        $message = Swift_Message::newInstance('Request for password retrieval')
                ->setFrom(array('railway.no.reply@gmail.com' => 'Railway Website Customer Service'))
                ->setTo($receiver)
                ->setBody($content, 'text/html');

        $result = $mailer->send($message);
        return $result;
    }
    
    public function sendEmailAccountCreation($receiver, $content) {
        $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
                ->setUsername('railway.no.reply@gmail.com')
                ->setPassword('Railway0123');

        $mailer = Swift_Mailer::newInstance($transport);

        $message = Swift_Message::newInstance('Railway Team Account Creation')
                ->setFrom(array('railway.no.reply@gmail.com' => 'Railway Website Customer Service'))
                ->setTo($receiver)
                ->setBody($content, 'text/html');

        $result = $mailer->send($message);
        return $result;
    }
    

    public function forgetPassword($user, $question, $answer) {
        $pstmtselect = $this->con->prepare($this->recoverpassword) or die($this->con->error);
        $pstmtupdate = $this->con->prepare($this->updatepassword) or die($this->con->error);
        $pstmtselect->bind_param('s', $user);
        $pstmtselect->execute();
        $pstmtselect->store_result();
        $pstmtselect->bind_result($this->uid, $this->username, $this->question, $this->answer, $this->email);
        if ($pstmtselect->fetch()) {
            if ($question == $this->question) {
                if ($answer == $this->answer) {
                    $password = Utilities::random_string();
                    $newpassword = hash('sha256', $this->salt . $password);
                    $content = '<p>Hi, ' . $this->username . '<br/>' .
                            'You have received this email because a user account password recovery was instigated by you on Railway Official Website</p>' .
                            '<br/>' .
                            '<p>IMPORTANT!<br/>' .
                            '-------------------------------------------<br/>' .
                            'If you did not request this password change, please report to us IMMEDIATELY.<br/>' .
                            '<p>The new password for your account is ' . $password . '. You are adviced to change your password after receiving this email.<br/>' .
                            'Please do not hesitate to contact us should you have any question regarding the website</p><br/><br/>' .
                            '<p>Regards, <br/>The Railway team.</p>';
                    $pstmtupdate->bind_param('ss', $newpassword, $this->uid);
                    $pstmtupdate->execute();
                    if ($pstmtupdate->affected_rows > 0) {
                        if ($this->sendEmail($this->email, $content) > 0) {
                            return 5;
                        }
                        return 4;
                    }
                    return 3;
                } else {
                    return 2;
                }
            } else {
                return 1;
            }
        } else {
            return 0;
        }
    }

    public function checkEmail() {
        $email = trim($_POST['email']);
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $pstmtselect = $this->con->prepare($this->checkemail);
            $pstmtselect->bind_param('s', $email);
            $pstmtselect->execute();
            if ($pstmtselect->fetch()) {
                $result = array(
                    'error' => true,
                    'message' => 'This email has been registered'
                );
                return $result;
            } else {
                $result = array(
                    'error' => false,
                    'message' => ''
                );
                return $result;
            }
        } else {
            $result = array(
                'error' => true,
                'message' => 'Invalid email'
            );
            return $result;
        }
    }

    public function checkUsername() {
        $username = trim($_POST['user']);
        $pstmtselect = $this->con->prepare($this->loginbyusername);
        $pstmtselect->bind_param('s', $username);
        $pstmtselect->execute();
        if ($pstmtselect->fetch()) {
            $result = array(
                'error' => true,
                'message' => 'This username has been registered'
            );
            return $result;
        } else {
            $result = array(
                'error' => false,
                'message' => ''
            );
            return $result;
        }
    }

}

?>
